// ❤ 三、函数式组件做地址增删改查
import React, { useEffect, useState } from 'react'
import axios from "axios";

// 引入组件
import AddressList from '../../components/AddressList';
import AddressAlert from '../../components/AddressAlert';

function My(props) {
  const [addressList, setAddress] = useState([]); //地址列表数据
  const [visible, setVisible] = useState(false); //弹框默认隐藏
  const [title, setTitle] = useState("新增地址");

  // 请求后端数据
  useEffect(() => {
    axios.get("/api/address").then(res => {
      setAddress(res.data)
    })
  }, [])

  // 1. 关闭弹框
  const onClose = () => {
    setVisible(false)
  }

  // 2. 点击弹框【提交】按钮，添加地址到列表页 

  const addAddress = (values) => {
    addressList.push({
      ...values,
      id: new Date() * 1,
      province: values.citys[0].name,
      city: values.citys[1].name,
      area: values.citys[2].name,
      isDefault: false, //是否选中
    })

    setAddress(addressList)
    console.log("addAddress", addressList);
  }

  // 3.删除
  const delAddress = (id) => {
    addressList.forEach((item, index) => {
      if (item.id === id) {
        addressList.splice(index, 1)
      }
    })

    setAddress([...addressList])
  }

  return (
    <div>
      {/* 1. 列表渲染  */}
      <AddressList
        addressList={addressList}
        delAddress={delAddress} //点击删除
      ></AddressList>
      {/* 2. 新增编辑弹窗  */}
      <AddressAlert
        visible={visible}
        title={title}
        onClose={onClose} //关闭弹框函数
        addAddress={addAddress} //点击提交新增地址

      ></AddressAlert>


      <button onClick={() => { //点击弹框出现
        setVisible(true)
      }}>新增地址</button>
    </div>
  )
}

export default My